﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Core.Extensibility;
using SeleniumToolkit.NUnit;
using NUnit.Core;
using System.Collections;
using System.Reflection;

namespace SeleniumToolkit.NUnit
{
    public class AddinUtil
    {
        public static void Uninstall()
        {
            ExtensionPoint suiteBuilders = CoreExtensions.Host.GetExtensionPoint("SuiteBuilders") as ExtensionPoint;
            ExtensionPoint eventListeners = CoreExtensions.Host.GetExtensionPoint("EventListeners") as ExtensionPoint;
            ExtensionPoint testBuilders = CoreExtensions.Host.GetExtensionPoint("TestCaseBuilders") as ExtensionPoint;

            RemoveExtension(typeof(SeleniumTestFixtureBuilder), suiteBuilders);
            RemoveExtension(typeof(SeleniumEventListener), eventListeners);
            RemoveExtension(typeof(WebTestCaseBuilder), testBuilders);

        }

        private static void RemoveExtension(Type type, ExtensionPoint extensionPoint)
        {
            IEnumerable items = GetInternalExtensions(extensionPoint);
            ArrayList toRemove = new ArrayList();

            foreach (object item in items)
            {
                if (type.IsAssignableFrom(item.GetType()))
                {
                    toRemove.Add(item);
                }
            }

            foreach (object item in toRemove)
            {
                extensionPoint.Remove(item);
            }
        }

        private static IEnumerable GetInternalExtensions(ExtensionPoint extensionPoint)
        {
            object extensions = extensionPoint.GetType().GetProperty("Extensions", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).GetValue(extensionPoint, new object[0]);
            return (IEnumerable)extensions;
        }
    }

}
